<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label{
    /*width: 130px;*/
    text-align: left;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }
  *{
    list-style:none;
  }
  #acts span {
    font-size: 14px;
  }
</style>
<template>
  <div class="comon">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      {{title}}
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <input type="hidden" name="entity.type" :value="type">
        <input v-if="type == 1" type="hidden" name="entity.departname" :value="depart.name" />
        <input v-if="type == 1" type="hidden" name="entity.departid" :value="depart.guid" />
        <div class="cellgroup">
          <template v-if="type == 1">
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">调出组织</label></div>
              <div class="weui-cell__bd">
                <input type="hidden" name="entity.orgid" :value="org1.guid" />
                <input type="hidden" name="entity.orgname" :value="org1.name" />
                <select class="weui-select rj-line-select" name="" v-model="org1">
                  <option value="" disabled>请选择</option>
                  <option v-for="(item, index) in organizations" :value="item">
                    {{item.name}}
                  </option>
                </select>
                <!--              <input type="hidden" name="entity.orgid" :value="formitem.orgguid">-->
                <!--              <input type="text" ref="org2" readonly class="weui-input" name="entity.orgname" :value="formitem.orgname">-->
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">调出库房</label></div>
              <div class="weui-cell__bd">
                <input type="hidden" name="entity.fromsrname" :value="room1.name" />
                <input type="hidden" name="entity.fromsrguid" :value="room1.guid" />
                <select class="weui-select"  v-model="room1">
                  <option value="" disabled>请选择</option>
                  <option selected=""  v-for="(item, index) in rooms1" :value="item">{{item.name}}</option>
                </select>
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">调入组织</label></div>
              <div class="weui-cell__bd">
                <input type="hidden" name="entity.toorgid" :value="org2.guid" />
                <input type="hidden" name="entity.toorgname" :value="org2.name" />
                <select class="weui-select rj-line-select" name="" v-model="org2">
                  <option value="" disabled>请选择</option>
                  <option v-for="(item, index) in organizations" :value="item">
                    {{item.name}}
                  </option>
                </select>
<!--                <input type="hidden" name="entity.toorgid" :value="toStr.orgguid">-->
<!--                <input type="text" ref="org3" readonly class="weui-input" name="entity.toorgname" :value="toStr.orgname">-->
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">调入库房</label></div>
              <div class="weui-cell__bd">
                <input type="hidden" name="entity.tosrguid" :value="toStr.guid">
                <input type="hidden" name="entity.tosrname" :value="toStr.name">
                <select class="weui-select" v-model="toStr">
                  <option value="" disabled>请选择</option>
                  <option selected=""  v-for="(item, index) in rooms2" :key="item.guid" :value="item">{{item.name}}</option>
                </select>
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">是否派车</label></div>
              <div class="weui-cell__bd">
                <select class="weui-select" ref="isSendCar" name="entity.isSendCar">
                  <option value="">请选择</option>
                  <option value="1">需要调度派车并结算运费</option>
                  <option value="2">不需要调度派车</option>
                </select>
              </div>
            </div>
          </template>
          <template v-if="type != 1">
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">{{fromSrTitle}}</label></div>
              <div class="weui-cell__bd">
                <input type="hidden" name="entity.fromsrname" :value="formitem.name">
                <input type="hidden" name="entity.fromsrguid" :value="formitem.guid">
                <select class="weui-select"  v-model="formitem" id="fromsr">
                  <option selected=""  v-for="(item, index) in rooms" :value="item">{{item.name}}</option>
                </select>
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">单据性质</label></div>
              <div class="weui-cell__bd">
                <select class="weui-select" name="entity.quality" v-model="quality">
                  <option v-for="(item, index) in qualitys" :value="item.dictkey" >{{item.dicttext}}</option>
                </select>
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">单据类型</label></div>
              <div class="weui-cell__bd">
                <select class="weui-select" name="entity.type" v-model="transferType">
                  <option v-for="(item, index) in transferTyps" :value="item.dictkey" >{{item.dicttext}}</option>
                </select>
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">库存组织</label></div>
              <div class="weui-cell__bd">
                <template v-if="transferType == 2">
                  <input type="hidden" name="entity.orgid" :value="org.guid">
                  <input type="hidden" ref="org1" name="entity.orgname" :value="org.name">
                  <select class="weui-select" v-model="org" id="org">
                    <option selected=""  v-for="(item, index) in organizations" :key="item.guid" :value="item">{{item.name}}</option>
                  </select>
                </template>
                <template v-else>
                  <input type="hidden" name="entity.orgid" :value="formitem.orgguid">
                  <input type="text" ref="org1" readonly class="weui-input" name="entity.orgname" :value="formitem.orgname">
                </template>
              </div>
            </div>
          </template>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" name="entity.remark" placeholder="请输备注内容" rows="2"></textarea>
            </div>
          </div>
        </div>
        <TransferApplyItem ref="applyItem" v-for="(item, index) in oitems" :key="index" :parentType="type" :itemNo="item" :isLast="index+1 == oitems.length" :roomid="formitem.guid" :transferType="transferType" @doAddItem="addItem(index + 1)" @doDelItem="delItem"></TransferApplyItem>
        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary halfbtn subbtn"  href="javascript:" @click="send">提交</a>
          <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  import TransferApplyItem from "./TransferApplyItem";
  import qs from 'qs';

  export default {
    name: 'AddTransferApply',
    data () {
      return {
        openid: localStorage.openid,
        organizations: [],
        departments: [],
        depart: "",
        rooms: [],
        oitems: [0],
        type: 1,
        fromsrguid: '',
        tosrguid: '',
        org: '',
        transferType: 1,
        toOrg: '',
        toStr: '',
        formitem: '',
        rooms1: [],
        rooms2: [],
        org1: '',
        room1: '',
        org2: '',
        room2: '',
        transferTyps: [],
        qualitys: [],
        quality: 1
      }
    },
    computed: {
      title: function() {
        return this.type == 1 ? '库房调拨录入' : '库存调整录入';
      },
      fromSrTitle: function() {
        return this.type == 1 ? '调出库房' : '库房';
      },
      showTosr: function() {
        return this.type == 1 ? true : false;
      }
    },
    components: {TransferApplyItem},
    created() {
      window.addEventListener('setItem', ()=> {
        this.openid = localStorage.getItem('openid');
      })
    },
    mounted () {
      //type 1-库房调拨，2，3-库存调整
      this.type = this.$route.query.type;

      //获取公司
      this.getOrganization();
      if (this.type == 1) {
        //获取部门
        this.getDepartment();
      } else {
        this.getRooms();
      }
      //获取单据性质数据
      this.getQualitys();
      //获取单据类型数据
      this.getTransTypes();
    },
    watch: {
      type: function (val) {
        if (val != 1) {
          this.transferType = 2;
        } else {
          this.transferType = 1;
        }
      },
      'formitem': function (val) {
        console.log('formitem:', val)
        console.log('formitem.orgname:', val.orgname)
        this.org = this.organizations.filter(item => {
          return item.guid == val.orgguid;
        })[0] || '';
      },
      // toStr: function (val) {
      //   this.toOrg = this.organizations.filter(item => {
      //     return item.guid == val.orgguid;
      //   })[0] || '';
      // },
      'org1.guid': function (val) {
        //获取库房
        this.getRooms(1, val);
      },
      'org2.guid': function (val) {
        //获取库房
        this.getRooms(2, val);
      }
    },
    methods: {
      getQualitys: function() {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Sellform!findDict.action',
          params: {type: 135}
        }).then(response => {
          if (response.statusText == "OK") {
            that.qualitys = response.data;
          } else {
            this.toastText('获取单据性质数据失败');
          }
        });
      },
      getTransTypes: function() {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Sellform!findDict.action',
          params: {type: 136}
        }).then(response => {
          if (response.statusText == "OK") {
            that.transferTyps = response.data;
          } else {
            this.toastText('获取单据类型数据失败');
          }
        });
      },
      addItem: function(index) {
        this.oitems.push(index);
      },
      delItem: function() {
        this.oitems.pop();
      },
      getOrganization: function() {
        this.axios({
          method: 'get',
          url: '/produce/Produceplan!getOrgbyWh.action',
          params: {}
        }).then((response) => {
          if (response.data.status == 'true') {
            this.organizations = response.data.result;
          } else if(response.data.status == 'false') {
            this.toastText(response.data.result);
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getDepartment: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDepartment.action',
          params: {sPermission: 3}
        }).then(response => {
          if (response.data.status == "true") {
            //that.departments = response.data.result.map(that.filterDepartment);
            that.departments = response.data.result;
            that.depart = response.data.result.length > 0 ? response.data.result[0] : '';
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastText('获取部门数据失败');
          }
        });
      },
      getRooms: function(type = '', orgid = '') {
        if (this.type == 1) {
          this.axios({
            method: 'get',
            url: '/produce/Storeroom!getStoreroom.action',
            params: {'entity.orgguid': orgid}
          }).then(response => {
            if (response.data.msg == 'success') {
              this['rooms' + type] = response.data.storeromms;
              // if (type == 1) {
              //   this.rooms1 = response.data.storeromms;
              // } else if (type == 2) {
              //   this.rooms2 = response.data.storeromms;
              // }
            } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
              //不不设置提示
            } else {
              this.toastText('获取库房数据失败');
            }
          });
        } else {
          this.axios({
            method: 'get',
            url: '/sales/Salespermission!getPermisForStore.action',
            params: {functionTypes: 5, type: 1}
          }).then(response => {
            if (response.data.msg == 'true') {
              this.rooms = response.data.storeroom;
              // this.formitem.guid = response.data.storeroom[0].guid;
              // this.$nextTick(function () {
              //   this.$refs.fromsrname.value = response.data.storeroom[0].name;
              // })
            } else if (response.data.msg == 'loginout') {
              this.toastText('请重新登录');
            } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
              //不不设置提示
            } else {
              this.toastText('获取库房数据失败');
            }
          });
        }
      },
      send: function() {
        let that = this;
        let productItem = this.$refs.applyItem;
        // if (this.type == 1 && this.depart == '') {
        //   this.toastText('当前用户没有所属部门！');
        //   return false;
        // }
        if (this.type == 1 && this.org1 == '') {
          this.toastText('调出组织不能为空！');
          return false;
        }
        if (this.type == 1 && this.room1 == '') {
          this.toastText('请选择调出库房！');
          return false;
        }
        if (this.type == 1 && this.org2 == '') {
          this.toastText('调入组织不能为空！');
          return false;
        }
        if (this.type == 1 && this.toStr == '') {
          this.toastText('请选择调入库房！');
          return false;
        }
        if (this.type == 1 && this.$refs.isSendCar.value == '') {
          this.toastText('请选择是否派车！');
          return false;
        }
        if (this.type != 1 && !this.checkNull(this.formitem)) {
          this.toastText('请选择库房！');
          return false;
        }
        if (this.type != 1 && !this.checkNull(this.$refs.org1.value)) {
          this.toastText('库存组织不能为空！');
          return false;
        }
        if (this.type != 1 && this.transferType != 2 && this.transferType != 3) {
          this.toastText('请选择调整类型！');
          return false;
        }
        if (!this.checkEmy('product')) {
          this.toastText('产品有误！');
          return false;
        }
        if (!this.checkEmy4('spec')) {
          this.toastText('规格有误！');
          return false;
        }
        if (!this.checkEmy('weight')) {
          this.toastText('重量有误！');
          return false;
        }
        // if (productItem[0].type == 2 && !this.checkEmy('spec')) {
        //   this.toastText('产品规格有误！');
        //   return false;
        // }
        if (!this.checkProduct()) {
          this.toastText('货品明细产品重复！')
          return false;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = this.serialize2Obj($("#formid").serializeArray());

        this.axios({
          method: 'post',
          url: '/produce/Transferapply!saveApplyInfo.action',
          data: qs.stringify(postData)
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if(response.data.msg == "success"){
            this.toastText('操作成功!');
            this.$router.push({name: 'TransferApplyList', query:{type: this.type}});
          }else if (response.data.msg == 'outlogin'){
            this.toastText('请重新登录!');
          }else if (response.data.msg == 'error'){
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });;

      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i = 0; i < $('.oitem').not(':hidden').length; i++) {
          parr1.push({
            [$('.product').eq(i).val()]: $('.spec').eq(i).val()
          });
          parr2.push({
            [$('.product').eq(i).val()]: $('.spec').eq(i).val()
          });
        }
        console.log('parr1:', parr1)
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j = i + 1; j < parr2.length;) {
            if (Object.keys(parr2[i])[0] == Object.keys(parr2[j])[0] && Object.values(parr2[i])[0] == Object.values(parr2[j])[0]) {
              parr2.splice(j, 1); //去除重复的对象；
            } else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      }
    }
  }


</script>
